package com.example.demo.biz.impl;

import com.example.demo.biz.PriceLadderBiz;
import com.example.demo.biz.PricePostcodeBiz;
import com.example.demo.domain.model.PriceLadder;
import com.example.demo.domain.model.PricePostcode;
import com.example.demo.domain.vo.PriceLadderVO;
import com.example.demo.mapper.PriceLadderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * -- 价格阶梯基础信息表业务实现
 *
 * @author zhiwen huang
 * @date 2020-12-23 23:04:09
 */
@Service
@Slf4j
public class PriceLadderBizImpl implements PriceLadderBiz {

    @Autowired
    private PriceLadderMapper priceLadderMapper;
    @Autowired
    private PricePostcodeBiz pricePostcodeBiz;


    /**
     * 根据id 查询
     *
     * @param id
     * @return
     */
    @Override
    public PriceLadder getById(Integer id) {
        if (null == id) {
            return null;
        }
        return priceLadderMapper.getById(id);
    }

    /**
     * 插入一条数据
     *
     * @param model
     * @return
     */
    @Override
    public void insert(PriceLadder model) {
        if (null == model) {
            return;
        }
        priceLadderMapper.insert(model);
    }

    /**
     * 根据id 更新不为null的参数,建议根据具体值更新对应的值
     * @param createTime
     * @return
     */
    //@Override
    //public int updateSelectiveById(PriceLadder model){
    //     if(null == model){
    //          return 0 ;
    //     }
    //    return priceLadderMapper.updateSelectiveBy(model);
    //}


    /**
     * 根据id列表 查询
     *
     * @param ids
     * @return
     */
    @Override
    public List<PriceLadder> listByIds(List<Integer> ids) {
        if (null == ids || ids.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        return priceLadderMapper.listByIds(ids);
    }

    @Override
    public List<PriceLadderVO> listAll() {

        return priceLadderMapper.listAll();
    }

    @Override
    @Transactional
    public void export(Map<Integer, String> headMap, List<Map<String, String>> dataMapList) {
        if (headMap == null || dataMapList.size() == 0) {
            return;
        }

        if (headMap.size() <= 3) {
            throw new RuntimeException("请按照格式上传");
        }

        List<String> postcodeList = new ArrayList<>(headMap.values());
        if (postcodeList.stream().filter(p -> p == null).findFirst().isPresent()) {
            throw new RuntimeException("数据不能为空");
        }

        if (dataMapList.stream().filter(p -> p == null).findFirst().isPresent()) {
            throw new RuntimeException("数据不能为空");
        }
        // TODO: 2020/12/24 导入数据格式校验,有效期大小校验，阶梯/编码重复性校验
        // TODO: 2020/12/24 导入数据 与已有数据重复性校验，阶梯/编码
        // TODO: 2020/12/24 下面导入流程只考虑纯新增

        Date date = new Date();
        List<PriceLadder> priceLadders = dataMapList.stream().map(d -> {
            PriceLadder priceLadder = new PriceLadder();
            priceLadder.setCreateTime(date);
            priceLadder.setDeleteFlag(0);
            try {
                priceLadder.setStartTime(initDateByDay(new SimpleDateFormat("yyyy/MM/dd").parse(d.get(1))));
                priceLadder.setEndTime(initDateByDay(new SimpleDateFormat("yyyy/MM/dd").parse(d.get(2))));
            } catch (ParseException e) {
//                e.printStackTrace();
                log.error("export...",e);
            }
            priceLadder.setLadderValue(new BigDecimal(d.get(0)));
            return priceLadder;
        }).collect(Collectors.toList());

        priceLadderMapper.batchInsert(priceLadders);

        List<PriceLadder> priceLadderList = priceLadderMapper.selectByLadderValueList(dataMapList.stream().map(d -> d.get(0)).collect(Collectors.toList()));
        Map<BigDecimal, Integer> nameMap = priceLadderList.stream().collect(Collectors.toMap(PriceLadder::getLadderValue, PriceLadder::getId));

        List<PricePostcode> pricePostcodes = new ArrayList<>();
        for (int i = 0; i < dataMapList.size(); i++) {
            Map<String, String> map = dataMapList.get(i);
            for (int z = 3; z < map.size(); z++) {
                PricePostcode pricePostcode = new PricePostcode();
                pricePostcode.setCreateTime(date);
                pricePostcode.setDeleteFlag(0);
                pricePostcode.setPostcode(headMap.get(z));
                pricePostcode.setPriceLadderId(nameMap.get(new BigDecimal(map.get(0)).setScale(3)));
                pricePostcode.setPrice(new BigDecimal(map.get(z)));
                pricePostcodes.add(pricePostcode);
            }
        }
        pricePostcodeBiz.batchInsert(pricePostcodes);

    }

    /**
     * 获得当天零时零分零秒
     *
     * @return
     */
    public static Date initDateByDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }


}
